package cn.suimg.shortlink.request;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 请求工具类
 */
public class RequestUtil {

    /**
     * Logger
     */
    private static Logger logger = LoggerFactory.getLogger(RequestUtil.class);

    /**
     * 获取当前请求对象
     *
     * @return
     */
    public static HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    /**
     * 获取当前响应对象
     *
     * @return
     */
    public static HttpServletResponse getResponse() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
    }

    /**
     * 获取当前Session
     *
     * @return
     */
    public static HttpSession getSession() {
        return getRequest().getSession();
    }

    /**
     * 获取Session中的字符串类型的数据
     *
     * @param name
     * @return
     */
    public static String getSession(String name) {
        return getSession(name, String.class);
    }

    /**
     * 获取Session中的数据
     *
     * @param name
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getSession(String name, Class<T> clazz) {
        return (T) getSession().getAttribute(name);
    }

    /**
     * 在Session中添加值
     *
     * @param name
     * @param value
     */
    public static void setSession(String name, Object value) {
        getSession().setAttribute(name, value);
    }

    /**
     * 清除属性
     *
     * @param name
     */
    public static void clearSession(String name) {
        getSession().removeAttribute(name);
    }

    /**
     * 设置属性
     *
     * @param name
     * @param value
     */
    public static void setAttribute(String name, Object value) {
        getRequest().setAttribute(name, value);
    }

    /**
     * 获取属性
     *
     * @param name
     * @param clazz
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T getAttribute(String name, Class<T> clazz) {
        return (T) getRequest().getAttribute(name);
    }

    /**
     * 获取属性
     *
     * @param name
     * @return
     */
    public static String getAttribute(String name) {
        return getAttribute(name, String.class);
    }

    /**
     * 清除属性
     *
     * @param name
     */
    public static void clearAttribute(String name) {
        getRequest().removeAttribute(name);
    }

    /**
     * 添加Cookie
     *
     * @param name
     * @param value
     */
    public static void setCookie(String name, String value) {
        Cookie cookie = new Cookie(name, value);
        getResponse().addCookie(cookie);
    }

    /**
     * 获取Cookie
     *
     * @param name
     * @return
     */
    public static String getCookie(String name) {
        Cookie[] cookies = getRequest().getCookies();
        if (cookies == null) {
            return null;
        }
        for (Cookie cookie : cookies) {
            if (cookie.getName().equalsIgnoreCase(name)) {
                return cookie.getValue();
            }
        }
        return null;
    }


    public static String getParameter(String name) {
        return getRequest().getParameter(name);
    }

    /**
     * 获取JSESSIONID
     *
     * @return
     */
    public static String getJSessionId() {
        return getCookie("JSESSIONID");
    }


    public static String getUserAgent(){
        return getRequest().getHeader("user-agent");
    }

    /**
     * 获取当前网络ip
     *
     * @return
     */
    public static String getIPAddress() {
        HttpServletRequest request = getRequest();
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            if ("127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip)) {
                // 根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                    ip = inet.getHostAddress();
                } catch (UnknownHostException e) {
                    logger.error(e.getMessage());
                }
            }
        }
        // 如果是多级代理，那么取第一个ip为客户ip
        if (ip != null && ip.indexOf(",") != -1) {
            ip = ip.substring(0, ip.indexOf(",")).trim();
        }
        return ip;
    }

    public static String getReferer() {
        return getRequest().getHeader("Referer");
    }

    /**
     * 输出文本到响应中
     *
     * @param text
     */
    public static void write(String text) {
        try {
            getResponse().getWriter().write(text);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }


    /**
     * 写出空白文档
     * @param content
     */
    public static void writeHtml(String content) {
        write(String.format("<!DOCTYPE html><html><head><meta charset=\"utf-8\"></head><body>%s</body></html>", content));
    }



}



